package com.study.demo.controller;

import com.study.demo.dao.DepartmentDao;
import com.study.demo.dao.EmployeeDao;
import com.study.demo.entities.Department;
import com.study.demo.entities.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Map;

/**
 * 员工相关
 * @author WS
 */
@Controller
public class EmployeeController {
    private Logger logger=LoggerFactory.getLogger(this.getClass());
    @Autowired
    private EmployeeDao dao;
    @Autowired
    private DepartmentDao departmentDao;
    /**
     * 查询员工列表
     * @return
     */
    @GetMapping("/emps")
    public String list(Map<String,Object> map){
        Collection<Employee> list =dao.getAll();
        map.put("emps",list);
        return "emp/list";
    }
    /**
     * 转向添加页面
     * @return
     */
    @GetMapping("/emp")
    public String toAddPage(Map<String,Object> map){
//        查出部门
        Collection<Department> departments = departmentDao.getDepartments();
        map.put("depts",departments);
        return "emp/add";
    }
    /**
     * 添加员工
     * @return
     */
    @PostMapping("/emp")
    public String add(Employee employee){
//        添加操作
        logger.info("------------>员工添加:"+employee);
        dao.save(employee);
        return "redirect:/emps";
    }
    /**
     * 转向修改页面
     * @return
     */
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Map<String,Object> map){
//        查出当前员工
        logger.info("修改的id"+id);
        Employee employee = dao.get(id);
        map.put("emp",employee);
        //        查出部门
        Collection<Department> departments = departmentDao.getDepartments();
        map.put("depts",departments);
        return "emp/add";
    }
    /**
     * 转向修改页面
     * @return
     */
    @PutMapping("/emp")
    public String edit(Employee employee){
//        查出当前员工
        logger.info("修改的员工:"+employee);
        dao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 删除员工
     * @return
     */
    @DeleteMapping("/emp/{id}")
    public String delete(@PathVariable("id")Integer id){
//        查出当前员工
        logger.info("删除的id:"+id);
        dao.delete(id);
        return "redirect:/emps";
    }
}
